//
//  NSString+MY.m
//  JQLive
//
//  Created by Bruce on 2020/3/26.
//  Copyright © 2020 mlqk. All rights reserved.
//

#import "NSString+MY.h"
#import "NSDate+NSDateFormatter.h"
//#import <LSRecorderAndProcessor/LSRecorderAndProcessor.h>

@implementation NSString (MY)


/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
- (NSMutableDictionary *)getURLParameters
{

    // 查找参数
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }

    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    // 截取参数
    NSString *parametersString = [self substringFromIndex:range.location + 1];

    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {

        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];

        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];

            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }

            id existValue = [params valueForKey:key];

            if (existValue != nil) {

                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];

                    [params setValue:items forKey:key];
                } else {

                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }

            } else {

                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数

        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];

        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }

        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];

        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }

        // 设置值
        [params setValue:value forKey:key];
    }

    return params;
}


- (NSString *)changeNumberFormat
{
    if (self.length <= 3) {
        return self;
    } else {
        NSMutableString *processString = [NSMutableString stringWithString:self];
        NSInteger location = processString.length - 3;
        NSMutableArray *processArray = [NSMutableArray array];
        while (location >= 0) {
            NSString *temp = [processString substringWithRange:NSMakeRange(location, 3)];
            [processArray addObject:temp];
            if (location < 3 && location > 0) {
                NSString *t = [processString substringWithRange:NSMakeRange(0, location)];
                [processArray addObject:t];
            }
            location -= 3;
        }
        NSMutableArray *resultsArray = [NSMutableArray array];
        int k = 0;
        for (NSString *str in processArray) {
            k++;
            NSMutableString *tmp = [NSMutableString stringWithString:str];
            if (str.length > 2 && k < processArray.count )
            {
                [tmp insertString:@"," atIndex:0];
                [resultsArray addObject:tmp];
            } else {
                [resultsArray addObject:tmp];
            }
        }
        NSMutableString *resultString = [NSMutableString string];
        for (NSInteger i = resultsArray.count - 1 ; i >= 0; i--) {
            NSString *tmp = [resultsArray objectAtIndex:i];
            [resultString appendString:tmp];
        }
        if ([resultString rangeOfString:@"."].length) {
            NSRange range = NSMakeRange(resultString.length - 4, 1);
            [resultString deleteCharactersInRange:range];
            return resultString;
        }else {
            return resultString;
        }
    }
}

+ (NSString *)getNowTimeTimestamp
{
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return timeSp;
}

/**
 把姓名转化成拼音且首字母大写
 */
- (NSString *)transformCharacter
{    
    NSMutableString *str = [self mutableCopy];
    CFStringTransform((CFMutableStringRef) str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinYin = [str stringByReplacingOccurrencesOfString:@" " withString:@""];;
    
    return [pinYin uppercaseString];
}

- (NSString *)formatterBankCardNum
{
    NSString *tempStr = self;
    NSInteger size = (tempStr.length / 4);
    NSMutableArray *tmpStrArr = [[NSMutableArray alloc] init];

    for (int n = 0; n < size; n++)
    {
        [tmpStrArr addObject:[tempStr substringWithRange:NSMakeRange(n*4, 4)]];
    }
    
    [tmpStrArr addObject:[tempStr substringWithRange:NSMakeRange(size*4, (tempStr.length % 4))]];
    tempStr = [tmpStrArr componentsJoinedByString:@" "];
    return tempStr;
}

+ (NSString *)getMonth
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate* dt = [NSDate date];
    unsigned unitFlags = NSCalendarUnitMonth;
    NSDateComponents* comp = [gregorian components:unitFlags fromDate:dt];
    return [NSString stringWithFormat:@"%ld",comp.month];
}

+ (NSString *)getYear
{
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy"];
    NSString *thisYearString = [dateformatter stringFromDate:senddate];
    return thisYearString;
}

+ (NSString *)getMonthAndYear
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate* dt = [NSDate date];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth;
    NSDateComponents* comp = [gregorian components:unitFlags fromDate:dt];
    return [NSString stringWithFormat:@"%02ld/%ld",comp.month,comp.year];
}

+ (NSString *)getMonthAndYear2
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate* dt = [NSDate date];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth;
    NSDateComponents* comp = [gregorian components:unitFlags fromDate:dt];
    return [NSString stringWithFormat:@"%ld年%ld月",comp.year,comp.month];
}

- (NSDate *)dateWithDateFormatString:(NSString *)formatString
{
    if(!formatString)
    {
        return nil;
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = formatString;
    return [formatter dateFromString:self];
}

- (NSMutableAttributedString *)formattingPriceWithMinFont:(NSInteger)min
{
    NSMutableAttributedString *priceAttrString = [[NSMutableAttributedString alloc] initWithString:self];
    
    if ([self containsString:@"¥"])
    {
        [priceAttrString addAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:min]} range:NSMakeRange(0, 1)];
    }
    
    [priceAttrString addAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:min]} range:NSMakeRange(self.length-3, 3)];
    
    return priceAttrString;
}

- (NSMutableAttributedString *)formattingDiscountPrice
{
    NSMutableAttributedString *priceAttrString = [[NSMutableAttributedString alloc] initWithString:self];
    [priceAttrString addAttributes:@{NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle),NSBaselineOffsetAttributeName : @0,NSStrikethroughStyleAttributeName : @(NSUnderlineStyleNone)} range:NSMakeRange(0, self.length)];
    return priceAttrString;
}

+ (NSString *)dateFormatStringHM:(NSInteger)time
{
    NSTimeInterval interval    = time;
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];
    NSString *dateString       = [formatter stringFromDate: date];
    return dateString;
}

//时间戳转时间字符串
+ (NSString *)dateFormatString:(NSInteger)time
{
    NSTimeInterval interval    = time;
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString       = [formatter stringFromDate: date];
    return dateString;
}

+ (NSInteger)dateFormatStringWithDayStart
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *currentDate = [NSDate date];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
    NSDate *zeroDate = [calendar dateFromComponents:components];
    NSInteger time = [zeroDate timeIntervalSince1970] + 86400 - [[NSDate date] timeIntervalSince1970];
    return time;
}

//时间字符串转时间戳
+ (NSString *)dateStringFormatTimeStamp:(NSString *)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *tempDate = [dateFormatter dateFromString:time];
    NSString *timeStr = [NSString stringWithFormat:@"%ld",(long)[tempDate timeIntervalSince1970]];
    return timeStr;
}

+ (NSString *)getDateWithYMD
{
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    NSString *string = [dateformatter stringFromDate:senddate];
    return string;
}

#pragma mark - 把大长串的数字做单位处理
+ (NSString *)changeAsset:(NSString *)amountStr

{

    if(amountStr && ![amountStr isEqualToString:@""])
    {
        NSInteger num = [amountStr integerValue];
        if(num >=1000000000000)
        {

            NSString *str = [NSString stringWithFormat:@"%0.2f",(double)num/1000000000000];
            return[NSString stringWithFormat:@"%@万亿",str ];
            
        } else if(num >=100000000)
        {
            NSString *str = [NSString stringWithFormat:@"%0.2f",(double)num/100000000];
            return[NSString stringWithFormat:@"%@亿",str];
            
        }
//        else if(num >=10000000)
//        {
//            NSString *str = [NSString stringWithFormat:@"%0.2f",(double)num/10000000];
//            return[NSString stringWithFormat:@"%@千万",str];
//
//        }
        else if(num >=10000)
        {
            NSString *str = [NSString stringWithFormat:@"%0.2f",(double)num/10000];
            return[NSString stringWithFormat:@"%@万",str];
            
        }
        
    }

    return amountStr;

}

//nim

+ (NSString *)timeStringWithSecond:(NSInteger)second
{
    NSInteger seconds = second % 60;
    NSInteger minutes = (second / 60) % 60;
    NSInteger hours = second / 3600;
    
    if (hours != 0)
    {
        return [NSString stringWithFormat:@"%02zi:%02zi:%02zi",hours, minutes, seconds];
    }
    else
    {
        return [NSString stringWithFormat:@"%02zi:%02zi",minutes, seconds];
    }
}
+ (NSString *)timeStringWithFormatSecond:(NSInteger)second
{
    NSInteger seconds = second % 60;
    NSInteger minutes = (second / 60) % 60;
    NSInteger hours = second / 3600;
    
    if (hours != 0)
    {
        return [NSString stringWithFormat:@"%zi小时%02zi分%02zi秒",hours, minutes, seconds];
    }
    else
    {
        if (minutes != 0) {
            return [NSString stringWithFormat:@"%zi分%02zi秒",minutes, seconds];
        }else{
            return [NSString stringWithFormat:@"%zi秒", seconds];
        }
        
    }
}
+ (NSString *)outputFileName
{
    NSDate *date = [NSDate date];
    NSString *dateStr = [date stringWithFormat:@"yyyyMMddHHmmss"];
    return [NSString stringWithFormat:@"%@.mp4", dateStr];
}

+ (NSString *)documentDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *rootPath = [paths firstObject];
    return rootPath;
}

+ (NSString *)documentSubDirectory:(NSString *)name;
{
    NSString *docDir = [NSString documentDirectory];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", docDir, name];
    BOOL isDirectory = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory]
        || !isDirectory)
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return filePath;
}

- (CGFloat)heightWithWidth:(CGFloat)width
{
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:self];
    NSRange range = NSMakeRange(0, attrStr.length);
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];
    CGSize sizeToFit = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                          options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                       attributes:dic
                                          context:nil].size;
    return sizeToFit.height;
}

//+ (NSString *)infoStringWithLSMediaRecordStatistics:(LSMediaRecordStatistics *)pStatistic
//{
//    NSString* statInfo = @"";
//    if (pStatistic)
//    {
//        NSString* filterFps = [[NSString alloc]initWithFormat:@"滤镜帧率: %d", (unsigned int)pStatistic.videoFilteredFrameRate];
//        NSString* encoderFps = [[NSString alloc]initWithFormat:@"编码帧率: %d", (unsigned int)pStatistic.videoSendFrameRate];
//        NSString* bitrate = [[NSString alloc]initWithFormat:@"码率: %d",(unsigned int) pStatistic.videoSendBitRate];
//        NSString* videoQuality = [[NSString alloc]initWithFormat:@"分辨率: %d x %d",
//                                  (unsigned int)pStatistic.videoSendWidth, (unsigned int)pStatistic.videoSendHeight];
//        statInfo = [[NSString alloc] initWithFormat:@" %@\n %@\n %@\n %@",
//                    videoQuality, filterFps,encoderFps,bitrate];
//    }
//    return statInfo;
//}


@end
